$(function(){
	// 获取数据
	$("#productLineId").text(deviceInfo.productLineName);
	$("#productLineId").attr("data-productLineId",deviceInfo.productLineId);
	$("#projectName").text(deviceInfo.projectName);
	$("#projectName").attr("data-projectId",deviceInfo.projectId);
	$("#deviceTypeId").text(deviceInfo.deviceTypeName);
	$("#deviceTypeId").attr("data-deviceTypeId",deviceInfo.deviceTypeId);
	deviceInfo = null;
	var str = '';
	for (var i = 0; i < rollData.length; i++) {
		str += '<div class="group-list">'+
					'<p class="deviceIdList" data-id="' + rollData[i].id + '" >' + rollData[i].name + '<i class="glyphicon glyphicon-remove-sign delList"></i></p>'+
				'</div>';
	}
	$(".deviceIdBox").html(str);
	getSubTaskData();

	// 保存
	$("#save").on("click",function(){
		var arrWOT = "";
		$(".workOrderType").each(function(){
			arrWOT += (this.value + ",");
		});
		var dataRule = {
			"deviceTypeId": Number($("#deviceTypeId").attr("data-deviceTypeId")),
			"workOrderTypeIds": arrWOT,
			"projectId": Number($("#projectName").attr("data-projectId"))
		};
		$.ajax({
            url: contextPath + '/ProcessRule/queryOrderTypeIdsNotExistProcessRule',
            type: 'get',
            cache : false,
            data: dataRule,
            contentType: "application/json",
            success: function (d) {
                if(d.code == 1){
					if (d.data.length != 0) {
						for (var i = 0; i < d.data.length; i++) {
							toastr.error("工单类型：" + d.data[i] + ' 没有指定相应规则！');
						}
						return;
					}else{
						var dl = [],
							sl = [];
						$(".deviceIdList").each(function () {
							dl.push($(this).attr("data-id"));
						});
						$(".subTask").each(function(){
							var temp = {
								"description": $(this).find(".description").val(),
							    "organizationId": Number($(this).find(".organizationId").attr("data-organizationId")),
							    "workOrderType": Number($(this).find(".workOrderType").val()),
								"checkTask": $(this).find("#check").prop('checked')?'是':'否'
                            }
							sl.push(temp);
						});
						if(dl.length == 0){
							toastr.error("所选设备不能为空！");
							return;
						}
						if(sl.length == 0){
							toastr.error("子任务不能为空！");
							return;
						}
						for (var i = 0; i < sl.length; i++) {
							if(!sl[i]["workOrderType"] || !sl[i]["organizationId"]){
								toastr.error("子任务信息不全！");
								return;
							}
							for (var j = i+1; j < sl.length; j++) {
								if(sl[i]["workOrderType"] == sl[j]["workOrderType"]){
									toastr.error("子任务工单类型不能相同！");
									return;
								}
							}
							if(sl[i]["description"].length > 250){
					    		toastr.error('子任务备注信息不能超过250个字符！！');
					    		return;
					    	}
						}
						var dataJson = {
							"deviceIdList": dl,
							"subTaskCreateVoList": sl
						};
						$.ajax({
				            url: contextPath + '/workorder/create',
				            type: 'POST',
				            cache : false,
				            data: JSON.stringify(dataJson),
				            contentType: "application/json",
				            success: function (data) {
				                if(data.code == 1){
				                    toastr.success('创建成功！');
				                    rollData = null;
				                    location.hash = "qualitycontrol-projectGroup-device";
				                }else{
				                    toastr.error(data.message,'创建失败！');
				                }
				            },
				            error: function (data) {
				                toastr.error(data.message,'创建失败！');
				                console.log(data);
				            } 
						});
					}
                }else{
                    toastr.error(d.message,'创建失败！');
                }
            },
            error: function (data) {
                toastr.error("操作失败，请稍后再试！");
                console.log(data);
            } 
		});
	});
	// 删除所选设备,删除子任务
	$(".form-box").on('click','.delList',function(){
		$(this).parent().parent().remove();
	});
	// 添加子任务
	$("#addSubTask").on('click',function(){
		var str = '<div class="form-group subTask">'+
					'<div class="group-head">'+
						'<p>子任务</p>'+
						'<i class="glyphicon glyphicon-remove-sign delList"></i>'+
					'</div>'+
					'<div class="group-body">'+
						'<div class="group-list">'+
							'<label for="workOrderType" class="form-label">工单类型:</label>'+
							'<select id="" name="workOrderType" class="form-input workOrderType" data-new="workOrderType">'+
								'<option value="">获取中…</option>'+
							'</select>'+
						'</div>'+
						'<div class="group-list">'+
							'<label for="organizationId" class="form-label">施工单位:</label>'+
							'<div class="tree-postion">'+
								'<input type="text" id="" name="organizationId" class="form-input organizationId" readonly placeholder="请选择">'+
								'<div id="menu-content" class="menu-content">'+
			                    	'<ul id="ztreeBox" class="ztree treeDemo" data-new="tree"></ul>'+
			                    '</div>'+
		                    '</div>'+
						'</div>'+
            			'<div class="group-list">'+
							'<label class="form-label">是否审核:</label>'+
            				'<input type="checkbox" id="check" name="check" class="" placeholder="是否需要审核任务" checked>'+
            			'</div>'+
						'<div class="group-list">'+
							'<label for="description" class="form-label">备注信息:</label>'+
							'<input type="text" id="" name="description" class="form-input description" placeholder>'+
						'</div>'+
					'</div>'+
				'</div>';
		$(".subTask_box").append(str);
		if(!_workOrderType || !_organizationId){
			getSubTaskData();
		}else{
			$("select[data-new='workOrderType']").html(_workOrderType).removeAttr("data-new");
			$.fn.zTree.init($("ul[data-new='tree']"), setting, _organizationId);
            $("ul[data-new='tree']").removeAttr("data-new");
		}
	});
});
var _workOrderType = "";
var _organizationId = "";
function getSubTaskData(){
	// 查询工单类型
	$.ajax({
        url: contextPath + "/WorkOrderType/queryAllWorkOrderType",
		type: "get",
        cache: false,
        dataType: "json",
        success: function(data){
            var str = '<option value="">请选择</option>';
            for (var i =0 ,len = data.length; i < len; i++) {
            	str += '<option value="' + data[i].id + '">' + data[i].name + "</option>";
            }
            _workOrderType = str;
            $("select[data-new='workOrderType']").html(str).removeAttr("data-new");
        },
        error: function(data){
            console.log(data);
            _workOrderType = '<option value="">数据异常</option>';
            $("select[data-new='workOrderType']").html('<option value="">数据异常</option>').removeAttr("data-new");
        }
    });
    // 查询施工单位
    $.ajax({
        url: contextPath + "/Organization/queryOrganizationTree",
		type: "get",
        cache: false,
        dataType: "json",
        success: function(data){
            _organizationId = data;
            $.fn.zTree.init($("ul[data-new='tree']"), setting, data);
            $("ul[data-new='tree']").removeAttr("data-new");
        },
        error: function(data){
            console.log(data);
            _organizationId = '<li value="">数据异常</li>';
            $("ul[data-new='tree']").html('<li value="">数据异常</li>').removeAttr("data-new");
        }
    });
    $(".form-box").on("click",".organizationId",function(){
    	toggle($(this));
    });
}
// 组织机构树配置
var setting = {
    view: {
        dblClickExpand: false,
        addDiyDom: function(treeId, treeNode){
        	$("ul[data-new='tree'] #" + treeNode.tId + "_a").attr("data-id",treeNode.id);
        }
    },
    data: {
        simpleData: {
            enable: true
        }
    }
};
// zTree点击事件
$(".subTask_box").on("click","a[treenode_a]",function(){
	var $this = $(this);
	$this.parents(".menu-content").siblings(".organizationId").val(this.title).attr("data-organizationId",$this.attr("data-id"));
});
/*function onClick(e, treeId, treeNode) {
	$(e.target).parents(".menu-content").siblings(".organizationId").val(treeNode.name).attr("data-organizationId",treeNode.id);
}*/
// 隐藏/显示 组织树
function toggle($this) {
    var menu_content = $this.siblings(".menu-content");
    if(menu_content.css("display") == 'none'){
        menu_content.slideDown("fast");
        $("body").on("mousedown", onBodyDown);
    }
}
function hideMenu() {
    $(".menu-content").fadeOut("fast");
    $("body").off("mousedown", onBodyDown);
}
function onBodyDown(event) {
    if (!(event.target.id == "ztreeBox" || event.target.id == "menu-content" || $(event.target).parents("#menu-content").length>0)) {
        hideMenu();
    }
}
